package com.zk.algorithm.bigdata;

import java.io.*;

public class FileUtils {

    /**
     * 文件读取监听器
     */
    public interface ReadListener {

        void onRead(String line, int lineNumber);

        void onReadCompleted();

    }

    /**
     * 一行一行地读取文件
     *
     * @param file
     * @param readListener
     * @throws IOException
     */
    public static void readFileLineByLine(File file, ReadListener readListener) throws IOException {
        int lineNumber = 1;

        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
            String line = null;

            while ((line = bufferedReader.readLine()) != null) {
                if (readListener != null) {
                    readListener.onRead(line, lineNumber);
                }
                lineNumber++;
            }
        }

        if (readListener != null) {
            readListener.onReadCompleted();
        }
    }

    /**
     * 往某个文件中追加一行
     *
     * @param file
     * @param line
     */
    public static void appendTo(File file, String line) throws IOException {
        makeSureFileExist(file);

        try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file))) {
            bufferedWriter.append(line);
            bufferedWriter.newLine();
        }
    }

    /**
     * 确保某个文件存在，不存在然后创建某个文件
     *
     * @param file
     * @throws IOException
     */
    public static void makeSureFileExist(File file) throws IOException {
        File parentFile = file.getParentFile();

        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }

        if (!file.exists()) {
            file.createNewFile();
        }
    }

    /**
     * 清空某个目录下的所有文件，但是不清理这个文件夹本身
     *
     * @param folder
     * @throws IOException
     */
    public static void removeAllFilesInFolder(File folder) throws IOException {
        org.apache.commons.io.FileUtils.cleanDirectory(folder);
    }

}
